﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FSM
{
    public string lastStateName = string.Empty;
    public Transform mTran;
    public BaseState _startState;
    public BaseState _curState;
    public BaseState _eventState;
    public BaseState _hangState;
    public List<BaseState> states = new List<BaseState>();

    public FSM()
    {
    }

    public BaseState AddState(BaseState state)
    {
        states.Add(state);
        state.Init(this);
        return state;
    }

    public string GetStateTransition()
    {
        string curName = _eventState != null ? _eventState.GetName() : (_curState != null ? _curState.GetName() : "Empty");
        return string.Format("{0}>{1}", lastStateName, curName);
    }

    public void Start(BaseState state)
    {
        _startState = state;
        _curState = state;
        _curState.Enter();
    }

    public void Run(float dt)
    {
        //执行事件状态
        if (_eventState != null)
        {
            if (_eventState.CheckExit())
            {
                _eventState.Exit();
                _eventState = null;
                if (_hangState != null && _hangState.CheckEnter())
                {
                    _curState = _hangState;
                    _curState.Enter();
                }
                else
                {
                    _curState = _startState;
                    _curState.Enter();
                }
                _hangState = null;
            }
            else
            {
                _eventState.Run(dt);
                return;
            }
        }

        //执行当前状态
        if (_curState != null)
        {
            if (_curState.CheckExit())
            {
                _curState.Exit();
                BaseState nextState = _curState.NextState();
                _curState = null;
                if (nextState != null)
                {
                    _curState = nextState;
                }
                else if (_startState.CheckEnter())
                {
                    _curState = _startState;
                }
                _curState.Enter();
            }
            _curState.Run(dt);
        }
    }

    public void SetEventState(AI_State key)
    {
        _eventState = GetState(key);
        if (_eventState != null && _eventState.CheckEnter())
        {
            if (_curState != null)
            {
                _curState.Exit();
                _hangState = _curState;
                _curState = null;
            }
            _eventState.Enter();
        }
    }

    public BaseState GetState(AI_State key)
    {
        foreach (var state in states)
        {
            if (state.mState == key)
            {
                return state;
            }
        }
        return null;
    }
}

public enum AI_State
{
    Wait,
    Track,
    Attack,
    Hit,
    Dead,
    Shoot,
}